package com.qin.mall.common.api;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import lombok.Data;

import java.util.ArrayList;
import java.util.List;

/** mybatis plus 分页信息
 * @author Leisure
 * create 2022 2022/11/21 10:29
 **/
@Data
public class MyBatisPlusPage<T> {
    private Long pageNum;
    private Long pageSize;
    private Long totalPage;
    private Long total;
    private List<T> list;


    public static <T> MyBatisPlusPage<T> mpPage(Page<T> list) {
        MyBatisPlusPage<T> result = new MyBatisPlusPage<T>();
        long total = list.getTotal();
        long size = list.getSize();
        long current = list.getCurrent();
        long pages = list.getPages();
        List<T> records =  list.getRecords();

        result.setTotal(total);
        result.setPageSize(size);
        result.setPageNum(current);
        result.setTotalPage(pages);
        result.setList(records);
        
        return  result;
    }

    public static <T> MyBatisPlusPage<T> getPages(Long currentPage, Long pageSize, List<T> list){
        MyBatisPlusPage<T> page = new MyBatisPlusPage<T>();
        Long size = Long.valueOf(list.size());
        if(pageSize > size){
            pageSize = size;
        }
        //求出最大页数，防止currentPage越界
        Long maxPage = size % pageSize == 0 ? size / pageSize : size / pageSize + 1;
        if(currentPage > maxPage){
            currentPage = maxPage;
        }
        //计算 当前页第一条数据下标
        Long curIds = currentPage > 1 ? (currentPage -1) * pageSize : 0;
        List pageList = new ArrayList<>();
        //将当前页的数据放进pageList
        for (int i = 0; i < pageSize && curIds + i < size; i++) {
            pageList.add(list.get((int) (curIds + i)));
        }
        long pages = pageList.size();
        //向page对象中手动设置各项分页的参数				
//        page.setCurrent(currentPage).
//                setSize(pageSize).
//                setTotal(list.size()).
//                setRecords(pageList);
        page.setPageNum(currentPage);
        page.setPageSize(pageSize);
        page.setTotal((long) list.size());
        page.setTotalPage(pages);
        page.setList(pageList);
        
        //计算分页总页数
        //page.setPages(size%pageSize == 0 ? size/pageSize :size/pageSize+1);
        return page;
        
        
    }

    




}
